<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="Dubbo支持在服务调用方对服务提供者采用负载均衡算法，LoadBalance 接口定义如下： 1234567891011121314@SPI(RandomLoadBalance.NAME)public interface LoadBalance &amp;#123;	&#x2F;**	 * select one invoker in list.	 * 	 * @param invokers invoke">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析Dubbo负载算法">
<meta property="og:url" content="https://www.codingw.net/posts/398539d9.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="Dubbo支持在服务调用方对服务提供者采用负载均衡算法，LoadBalance 接口定义如下： 1234567891011121314@SPI(RandomLoadBalance.NAME)public interface LoadBalance &amp;#123;	&#x2F;**	 * select one invoker in list.	 * 	 * @param invokers invoke">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdn.net/20180706123312775?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20180706123621108?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20180706124209836?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20180706124240681?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="article:published_time" content="2020-11-03T15:31:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:09:57.460Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdn.net/20180706123312775?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/398539d9.html"/>





  <title>源码分析Dubbo负载算法 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/398539d9.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析Dubbo负载算法</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-03T23:31:01+08:00">
                2020-11-03
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/dubbo/" itemprop="url" rel="index">
                    <span itemprop="name">dubbo</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/398539d9.html" class="leancloud_visitors" data-flag-title="源码分析Dubbo负载算法">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>Dubbo支持在服务调用方对服务提供者采用负载均衡算法，LoadBalance 接口定义如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">@SPI(RandomLoadBalance.NAME)</span><br><span class="line">public interface LoadBalance &#123;</span><br><span class="line"></span><br><span class="line">	&#x2F;**</span><br><span class="line">	 * select one invoker in list.</span><br><span class="line">	 * </span><br><span class="line">	 * @param invokers invokers.</span><br><span class="line">	 * @param url refer url</span><br><span class="line">	 * @param invocation invocation.</span><br><span class="line">	 * @return selected invoker.</span><br><span class="line">	 *&#x2F;</span><br><span class="line">    @Adaptive(&quot;loadbalance&quot;)</span><br><span class="line">	&lt;T&gt; Invoker&lt;T&gt; select(List&lt;Invoker&lt;T&gt;&gt; invokers, URL url, Invocation invocation) throws RpcException;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从中透露出如下几个信息：默认如果不配置，使用RandomLoadBalance策略(加权随机负载算法）。整个Dubbo的负载均衡类图如下所示：<br><img src="https://img-blog.csdn.net/20180706123312775?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br>上述各种路由负载策略，对应的配置值如下：dubbo-cluster\src\main\resources\META-INF\dubbo\internal\com.alibaba.dubbo.rpc.cluster.LoadBalance</p>
<ul>
<li>random<br> random=com.alibaba.dubbo.rpc.cluster.loadbalance.RandomLoadBalance</li>
<li>roundrobin<br> roundrobin=com.alibaba.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance</li>
<li>leastactive<br> leastactive=com.alibaba.dubbo.rpc.cluster.loadbalance.LeastActiveLoadBalance</li>
<li>consistenthash<br>consistenthash=com.alibaba.dubbo.rpc.cluster.loadbalance.ConsistentHashLoadBalance<br>其配置使用，通常一般在&lt; dubbo:consumer/&gt;、&lt; dubbo:service /&gt;、&lt; dubbo:reference /&gt;的loadbalance属性配置，通常&lt; dubbo:consumer/&gt;这个属性指定消费端的默认策略，某些服务需要指定特殊负载均衡策略的话，一般通过&lt; dubbo:reference /&gt;来指定。<br>如果各位对其源码实现比较有兴趣的话，可以看接下来的部分，源码分析各种负载算法的具体实现细节。</li>
</ul>
<h2 id="1、源码分析ConsistentHashLoadBalance（一致性Hash算法）"><a href="#1、源码分析ConsistentHashLoadBalance（一致性Hash算法）" class="headerlink" title="1、源码分析ConsistentHashLoadBalance（一致性Hash算法）"></a>1、源码分析ConsistentHashLoadBalance（一致性Hash算法）</h2><p><img src="https://img-blog.csdn.net/20180706123621108?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br>一致Hash算法，通常用在缓存领域，主要解决的问题是当数据节点数量发送变化后，尽量减少数据的迁移，在负责算法领域，个人不建议使用。Dubbo一致性Hash算法的实现逻辑主要分布在ConsistentHashLoadBalance$ConsistentHashSelector中。</p>
<h3 id="1-1-核心属性与构造方法"><a href="#1-1-核心属性与构造方法" class="headerlink" title="1.1 核心属性与构造方法"></a>1.1 核心属性与构造方法</h3><span id="more"></span>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">private final TreeMap&lt;Long, Invoker&lt;T&gt;&gt; virtualInvokers;</span><br><span class="line">private final int                       replicaNumber;</span><br><span class="line">private final int                       identityHashCode;</span><br><span class="line">private final int[]                     argumentIndex;</span><br></pre></td></tr></table></figure>
<p>TreeMap&lt; Long, Invoker&lt; T&gt;&gt; virtualInvokers：虚拟节点，使用TreeMap实现Hash环，将Invoker分布在环上。</p>
<ul>
<li>int                       replicaNumber：虚拟节点个数。</li>
<li> int                       identityHashCode：HashCode。</li>
<li>int[]                     argumentIndex：需要参与hash的参数索引,,argumentIndex = [0,1]表示服务方法的第一个，第二个参数参与hashcode计算。<br>接下来看一下其构造方法：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">public ConsistentHashSelector(List&lt;Invoker&lt;T&gt;&gt; invokers, String methodName, int identityHashCode) &#123;</span><br><span class="line">    this.virtualInvokers &#x3D; new TreeMap&lt;Long, Invoker&lt;T&gt;&gt;();</span><br><span class="line">    this.identityHashCode &#x3D; System.identityHashCode(invokers);    &#x2F;&#x2F; @1</span><br><span class="line">    URL url &#x3D; invokers.get(0).getUrl();</span><br><span class="line">    this.replicaNumber &#x3D; url.getMethodParameter(methodName, &quot;hash.nodes&quot;, 160);   &#x2F;&#x2F; @2</span><br><span class="line">    String[] index &#x3D; Constants.COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, &quot;hash.arguments&quot;, &quot;0&quot;));   &#x2F;&#x2F; @3 start</span><br><span class="line">    argumentIndex &#x3D; new int[index.length];</span><br><span class="line">    for (int i &#x3D; 0; i &lt; index.length; i ++) &#123;</span><br><span class="line">          argumentIndex[i] &#x3D; Integer.parseInt(index[i]);</span><br><span class="line">    &#125;  &#x2F;&#x2F; @3 end</span><br><span class="line">    for (Invoker&lt;T&gt; invoker : invokers) &#123;    &#x2F;&#x2F; @4</span><br><span class="line">         for (int i &#x3D; 0; i &lt; replicaNumber &#x2F; 4; i++) &#123;</span><br><span class="line">               byte[] digest &#x3D; md5(invoker.getUrl().toFullString() + i);</span><br><span class="line">               for (int h &#x3D; 0; h &lt; 4; h++) &#123; </span><br><span class="line">                     long m &#x3D; hash(digest, h);</span><br><span class="line">                     virtualInvokers.put(m, invoker);  </span><br><span class="line">                &#125;</span><br><span class="line">           &#125;</span><br><span class="line">      &#125; &#x2F;&#x2F; @4 end</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：根据所有的调用者生成一个HashCode，用该HashCode值来判断服务提供者是否发生了变化。</p>
<p>代码@2：获取服务提供者&lt; dubbo:method/&gt;标签的hash.nodes属性，如果为空，默认为160，表示一致性hash算法中虚拟节点数量。其配置方式如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt; dubbo:method ... &gt;</span><br><span class="line">    &lt; dubbo:parameter key&#x3D;&quot;hash.nodes&quot; value&#x3D;&quot;160&quot; &#x2F;&gt;</span><br><span class="line">    &lt; dubbo:parameter key&#x3D;&quot;hash.arguments&quot; value&#x3D;&quot;0,1&quot; &#x2F;&gt;</span><br><span class="line">&lt; &#x2F;dubbo:method&#x2F;&gt;</span><br></pre></td></tr></table></figure>

<p>代码@3：一致性Hash算法，在dubbo中，相同的服务调用参数走固定的节点，hash.arguments表示哪些参数参与hashcode，默认值“0”，表示第一个参数。</p>
<p>代码@4：为每一个Invoker创建replicaNumber 个虚拟节点，每一个节点的Hashcode不同。同一个Invoker不同hashcode的创建逻辑为：invoker.getUrl().toFullString() + i (0-39) 的值，对其md5,然后用该值+h(0-3)的值取hash。一致性hash实现的一个关键是如果将一个Invoker创建的replicaNumber 个虚拟节点(hashcode)能够均匀分布在Hash环上，Dubbo给出的实现如下，由于能力有限，目前并未真正理解如下方法的实现依据：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">private long hash(byte[] digest, int number) &#123;</span><br><span class="line">            return (((long) (digest[3 + number * 4] &amp; 0xFF) &lt;&lt; 24)</span><br><span class="line">                    | ((long) (digest[2 + number * 4] &amp; 0xFF) &lt;&lt; 16)</span><br><span class="line">                    | ((long) (digest[1 + number * 4] &amp; 0xFF) &lt;&lt; 8)</span><br><span class="line">                    | (digest[number * 4] &amp; 0xFF))</span><br><span class="line">                    &amp; 0xFFFFFFFFL;</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
<p>综上所述，构造函数主要完成一致性Hash算法Hash环的构建，利用了TreeMap的有序性来实现。</p>
<h3 id="1-2-源码分析public-Invoker-lt-T-gt-select-Invocation-invocation"><a href="#1-2-源码分析public-Invoker-lt-T-gt-select-Invocation-invocation" class="headerlink" title="1.2 源码分析public Invoker&lt; T&gt; select(Invocation invocation)"></a>1.2 源码分析public Invoker&lt; T&gt; select(Invocation invocation)</h3><p>根据调用环境根据一致性Hash算法选择一个Invoker</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">public Invoker&lt;T&gt; select(Invocation invocation) &#123;</span><br><span class="line">     String key &#x3D; toKey(invocation.getArguments());   &#x2F;&#x2F; @1</span><br><span class="line">     byte[] digest &#x3D; md5(key);                                      &#x2F;&#x2F; @2</span><br><span class="line">     return selectForKey(hash(digest, 0));                   &#x2F;&#x2F; @3</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：根据调用参数，并根据hash.arguments配置值，获取指定的位置的参数值，追加一起返回。<br>代码@2：对Key进行md5签名。<br>代码@3：根据key进行选择调用者。</p>
<h4 id="1-2-1-ConsistentHashLoadBalance-ConsistentHashSelector-selectForKey"><a href="#1-2-1-ConsistentHashLoadBalance-ConsistentHashSelector-selectForKey" class="headerlink" title="1.2.1 ConsistentHashLoadBalance$ConsistentHashSelector#selectForKey"></a>1.2.1 ConsistentHashLoadBalance$ConsistentHashSelector#selectForKey</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">private Invoker&lt;T&gt; selectForKey(long hash) &#123;</span><br><span class="line">     Map.Entry&lt;Long, Invoker&lt;T&gt;&gt; entry &#x3D; virtualInvokers.tailMap(hash, true).firstEntry();    &#x2F;&#x2F; @1</span><br><span class="line">     if (entry &#x3D;&#x3D; null) &#123;    &#x2F;&#x2F; @2</span><br><span class="line">     	entry &#x3D; virtualInvokers.firstEntry();</span><br><span class="line">     &#125;</span><br><span class="line">     return entry.getValue();   &#x2F;&#x2F; @3</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1，对虚拟节点，从virtualInvokers中选取一个子集，subMap(hash,ture,lastKey,true),其实就是实现根据待查找hashcode(key)顺时针，选中大于等于指定key的第一个key。<br>代码@2，如果未找到，则返回virtualInvokers第一个key。<br>代码@3：根据key返回指定的Invoker即可。<br>这里实现，应该可以不使用tailMap，代码修改如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">private Invoker&lt;T&gt; selectForKey(long hash) &#123;</span><br><span class="line">     Map.Entry&lt;Long, Invoker&lt;T&gt;&gt; entry &#x3D; virtualInvokers.ceilingEntry(hash);</span><br><span class="line">     if(entry &#x3D;&#x3D; null ) &#123;</span><br><span class="line">     	entry &#x3D; virtualInvokers.firstEntry();</span><br><span class="line">     &#125;</span><br><span class="line">     return entry.getValue();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果想要了解TreeMap关于这一块的特性(tailMap、ceillingEntry、headMap)等API的详细解释，可以查看我的另外一篇博文：<a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/80821576">https://blog.csdn.net/prestigeding/article/details/80821576</a></p>
<h2 id="2、源码分析RandomLoadBalance"><a href="#2、源码分析RandomLoadBalance" class="headerlink" title="2、源码分析RandomLoadBalance"></a>2、源码分析RandomLoadBalance</h2><h3 id="2-1-Dubbo预热机制（权重）"><a href="#2-1-Dubbo预热机制（权重）" class="headerlink" title="2.1 Dubbo预热机制（权重）"></a>2.1 Dubbo预热机制（权重）</h3><p>由于roundrobin（加权轮询）、random（加权随机）、leastactive（最小活跃连接数）都与权重有关系，在介绍这两种负载均衡算法之前，我们首先看一下Dubbo关于权重的获取逻辑，代码见AbstractLoadBalance#getWeigh方法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">protected int getWeight(Invoker&lt;?&gt; invoker, Invocation invocation) &#123;</span><br><span class="line">        int weight &#x3D; invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT);   &#x2F;&#x2F; @1</span><br><span class="line">        if (weight &gt; 0) &#123;</span><br><span class="line">            long timestamp &#x3D; invoker.getUrl().getParameter(Constants.REMOTE_TIMESTAMP_KEY, 0L);  &#x2F;&#x2F; @2</span><br><span class="line">            if (timestamp &gt; 0L) &#123;</span><br><span class="line">                int uptime &#x3D; (int) (System.currentTimeMillis() - timestamp);</span><br><span class="line">                int warmup &#x3D; invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP);  &#x2F;&#x2F; @3</span><br><span class="line">                if (uptime &gt; 0 &amp;&amp; uptime &lt; warmup) &#123;</span><br><span class="line">                    weight &#x3D; calculateWarmupWeight(uptime, warmup, weight);   &#x2F;&#x2F; @4</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return weight;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先获取服务提供者的权重(weight)。</p>
<p>代码@2：获取服务提供者的启动时间，在服务提供者启动时，会将启动时间戳存储在服务提供者的URL中，在服务发现(RegistryDirecotry)服务发现时，会将服务提供者的时间戳KEY，换成REMOTE_TIMESTAMP_KEY，避免与服务消费者的启动时间戳冲突。</p>
<p>代码@3：获取服务提供者是否开启预热机制，通过服务提供者&lt; dubbo:service warmup=””/&gt;参数来设置，如果未设置，去默认值10 * 60 * 1000（10分钟）。</p>
<p>代码@4：如果服务提供者启动时间小于预热时间（预热期间），需要根据启动时间，来计算预热期间服务提供者的权重。<br>AbstractLoadBalance#calculateWarmupWeight</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">static int calculateWarmupWeight(int uptime, int warmup, int weight) &#123; &#x2F;&#x2F; @1</span><br><span class="line">        int ww &#x3D; (int) ((float) uptime &#x2F; ((float) warmup &#x2F; (float) weight));</span><br><span class="line">        return ww &lt; 1 ? 1 : (ww &gt; weight ? weight : ww);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：参数说明，uptime：服务提供者启动时间；warmup：设置的预热时间;weight：服务提供者的权重，该方法在uptime &lt; warmup时被调用<br>该方法的实现，就是在预热期间，根据启动时间，动态返回该服务提供者的权重，并且启动时间越长，返回的权重越接近weight，启动时间超过预热时间，则直接返回weight。<br>该方法单元测试：<br><img src="https://img-blog.csdn.net/20180706124209836?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br>其输出结果：<br><img src="https://img-blog.csdn.net/20180706124240681?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"></p>
<h3 id="2-2-RandomLoadBalance-加权随机算法实现分析"><a href="#2-2-RandomLoadBalance-加权随机算法实现分析" class="headerlink" title="2.2 RandomLoadBalance 加权随机算法实现分析"></a>2.2 RandomLoadBalance 加权随机算法实现分析</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">protected &lt;T&gt; Invoker&lt;T&gt; doSelect(List&lt;Invoker&lt;T&gt;&gt; invokers, URL url, Invocation invocation) &#123;</span><br><span class="line">        int length &#x3D; invokers.size(); &#x2F;&#x2F; Number of invokers                    </span><br><span class="line">        int totalWeight &#x3D; 0; &#x2F;&#x2F; The sum of weights       &#x2F;&#x2F; @1 start</span><br><span class="line">        boolean sameWeight &#x3D; true; &#x2F;&#x2F; Every invoker has the same weight?</span><br><span class="line">        for (int i &#x3D; 0; i &lt; length; i++) &#123;</span><br><span class="line">            int weight &#x3D; getWeight(invokers.get(i), invocation);</span><br><span class="line">            totalWeight +&#x3D; weight; &#x2F;&#x2F; Sum</span><br><span class="line">            if (sameWeight &amp;&amp; i &gt; 0</span><br><span class="line">                    &amp;&amp; weight !&#x3D; getWeight(invokers.get(i - 1), invocation)) &#123;</span><br><span class="line">                sameWeight &#x3D; false;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;   &#x2F;&#x2F; @1 end</span><br><span class="line">        if (totalWeight &gt; 0 &amp;&amp; !sameWeight) &#123;    &#x2F;&#x2F; @2</span><br><span class="line">            &#x2F;&#x2F; If (not every invoker has the same weight &amp; at least one invoker&#39;s weight&gt;0), select randomly based on totalWeight.</span><br><span class="line">            int offset &#x3D; random.nextInt(totalWeight);</span><br><span class="line">            &#x2F;&#x2F; Return a invoker based on the random value.</span><br><span class="line">            for (int i &#x3D; 0; i &lt; length; i++) &#123;</span><br><span class="line">                offset -&#x3D; getWeight(invokers.get(i), invocation);</span><br><span class="line">                if (offset &lt; 0) &#123;</span><br><span class="line">                    return invokers.get(i);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        &#x2F;&#x2F; If all invokers have the same weight value or totalWeight&#x3D;0, return evenly.</span><br><span class="line">        return invokers.get(random.nextInt(length));  &#x2F;&#x2F; @3</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先求所有服务提供者的总权重，并判断每个服务提供者的权重是否相同。</p>
<p>代码@2：如果提供者之间的权重不相同，则产生一个随机数(0-totalWeight)，视为offset,然后依次用offset减去服务提供者的权重，如果减去(offset - provider.weight &lt; 0),则该invoker命中。</p>
<p>代码@3：如果服务提供者的权重相同，则随机产生[0-invoker.size)即可。</p>
<h3 id="2-3-RoundRobinLoadBalance-加权轮询算法分析"><a href="#2-3-RoundRobinLoadBalance-加权轮询算法分析" class="headerlink" title="2.3 RoundRobinLoadBalance 加权轮询算法分析"></a>2.3 RoundRobinLoadBalance 加权轮询算法分析</h3><p>加权轮询算法的核心算法是按权重轮询，一个基本点是应该是一个当前序号与服务提供者数量取模，需要结合权重。Dubbo使用如下数据结构存储当前序号：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">private final ConcurrentMap&lt;String, AtomicPositiveInteger&gt; sequences &#x3D; new ConcurrentHashMap&lt;String, AtomicPositiveInteger&gt;();键值：serviceKey(&lt;dubbo:service interface&#x3D;&quot;&quot;&#x2F;&gt;+ methodname)，每个方法采用不同的计数器。</span><br><span class="line">RoundRobinLoadBalance #doSelect</span><br><span class="line">protected &lt;T&gt; Invoker&lt;T&gt; doSelect(List&lt;Invoker&lt;T&gt;&gt; invokers, URL url, Invocation invocation) &#123;</span><br><span class="line">        String key &#x3D; invokers.get(0).getUrl().getServiceKey() + &quot;.&quot; + invocation.getMethodName();    &#x2F;&#x2F; @1</span><br><span class="line">        int length &#x3D; invokers.size(); &#x2F;&#x2F; Number of invokers</span><br><span class="line">        int maxWeight &#x3D; 0; &#x2F;&#x2F; The maximum weight</span><br><span class="line">        int minWeight &#x3D; Integer.MAX_VALUE; &#x2F;&#x2F; The minimum weight</span><br><span class="line">        final LinkedHashMap&lt;Invoker&lt;T&gt;, IntegerWrapper&gt; invokerToWeightMap &#x3D; new LinkedHashMap&lt;Invoker&lt;T&gt;, IntegerWrapper&gt;();   &#x2F;&#x2F; @2 start</span><br><span class="line">        int weightSum &#x3D; 0;</span><br><span class="line">        for (int i &#x3D; 0; i &lt; length; i++) &#123;</span><br><span class="line">            int weight &#x3D; getWeight(invokers.get(i), invocation);</span><br><span class="line">            maxWeight &#x3D; Math.max(maxWeight, weight); &#x2F;&#x2F; Choose the maximum weight</span><br><span class="line">            minWeight &#x3D; Math.min(minWeight, weight); &#x2F;&#x2F; Choose the minimum weight</span><br><span class="line">            if (weight &gt; 0) &#123;</span><br><span class="line">                invokerToWeightMap.put(invokers.get(i), new IntegerWrapper(weight));</span><br><span class="line">                weightSum +&#x3D; weight;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;   &#x2F;&#x2F; @2 end </span><br><span class="line">        AtomicPositiveInteger sequence &#x3D; sequences.get(key);</span><br><span class="line">        if (sequence &#x3D;&#x3D; null) &#123;</span><br><span class="line">            sequences.putIfAbsent(key, new AtomicPositiveInteger());</span><br><span class="line">            sequence &#x3D; sequences.get(key);</span><br><span class="line">        &#125;</span><br><span class="line">        int currentSequence &#x3D; sequence.getAndIncrement();    &#x2F;&#x2F; @3</span><br><span class="line">        if (maxWeight &gt; 0 &amp;&amp; minWeight &lt; maxWeight) &#123;   &#x2F;&#x2F; @4</span><br><span class="line">            int mod &#x3D; currentSequence % weightSum;</span><br><span class="line">            for (int i &#x3D; 0; i &lt; maxWeight; i++) &#123;</span><br><span class="line">                for (Map.Entry&lt;Invoker&lt;T&gt;, IntegerWrapper&gt; each : invokerToWeightMap.entrySet()) &#123;</span><br><span class="line">                    final Invoker&lt;T&gt; k &#x3D; each.getKey();</span><br><span class="line">                    final IntegerWrapper v &#x3D; each.getValue();</span><br><span class="line">                    if (mod &#x3D;&#x3D; 0 &amp;&amp; v.getValue() &gt; 0) &#123;</span><br><span class="line">                        return k;</span><br><span class="line">                    &#125;</span><br><span class="line">                    if (v.getValue() &gt; 0) &#123;</span><br><span class="line">                        v.decrement();</span><br><span class="line">                        mod--;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        &#x2F;&#x2F; Round robin</span><br><span class="line">        return invokers.get(currentSequence % length);   &#x2F;&#x2F; @5</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：构建ConcurrentMap&lt; String, AtomicPositiveInteger&gt; sequences中的key,以interface+methodname为键，里面存储的是当前序号（轮询）。</p>
<p>代码@2：构建LinkedHashMap&lt; Invoker&lt; T&gt;, IntegerWrapper&gt;存储结构，通过遍历所有Invoker，构建每个Invoker的权重，与此同时算出总权重，并且得出所有服务提供者权重是否相同。</p>
<p>代码@3：获取当前的轮询序号，用于取模。</p>
<p>代码@4：如果服务提供者之间的权重有差别，需要按权重轮询，实现方式是：</p>
<ul>
<li>用当前轮询序号与服务提供者总权重取模，余数为mod。</li>
<li>然后从0循环直到最大权重，针对每一次循环，按同一顺序遍历所有服务提供者，如果mod等于0并且对应的Invoker的权重计算器大于0，则选择该服务提供者；否则，mod–,invoker对应的权重减一，权重是临时比那里LinkedHashMap&lt; Invoker&lt; T&gt;, IntegerWrapper&gt;。由于外层循环的次数为所有服务提供者的最大权重，内层循环当mod等于0时，肯定会有一个服务提供者的权重计数器大于0,而返回对应的服务提供者。返回的服务提供者是第一个满足的服务提供者，后续的服务提供者在下一次就会有机会， 因为下一次mod会增大1，后续的服务提供者通过轮询会被选择，选择的机会，取决于权重的大小。</li>
</ul>
<p>代码@5：如果各服务提供者权重相同，则直接对服务提供者取模即可，轮询后递增。</p>
<h3 id="2-4-LeastActiveLoadBalance"><a href="#2-4-LeastActiveLoadBalance" class="headerlink" title="2.4 LeastActiveLoadBalance"></a>2.4 LeastActiveLoadBalance</h3><p>最少活跃连接数负载均衡算法分析，最小活跃连接数，其核心实现就是，首先找到服务提供者当前最小的活跃连接数，如果一个服务提供者的服务连接数比其他的都要小，则选择这个活跃连接数最小的服务提供者发起调用，如果存在多个服务提供者的活跃连接数，并且是最小的，则在这些服务提供者之间选择加权随机算法选择一个服务提供者。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">protected &lt;T&gt; Invoker&lt;T&gt; doSelect(List&lt;Invoker&lt;T&gt;&gt; invokers, URL url, Invocation invocation) &#123;</span><br><span class="line">        int length &#x3D; invokers.size(); &#x2F;&#x2F; Number of invokers                                                                                            &#x2F;&#x2F; @1 start</span><br><span class="line">        int leastActive &#x3D; -1; &#x2F;&#x2F; The least active value of all invokers</span><br><span class="line">        int leastCount &#x3D; 0; &#x2F;&#x2F; The number of invokers having the same least active value (leastActive)</span><br><span class="line">        int[] leastIndexs &#x3D; new int[length]; &#x2F;&#x2F; The index of invokers having the same least active value (leastActive)</span><br><span class="line">        int totalWeight &#x3D; 0; &#x2F;&#x2F; The sum of weights</span><br><span class="line">        int firstWeight &#x3D; 0; &#x2F;&#x2F; Initial value, used for comparision</span><br><span class="line">        boolean sameWeight &#x3D; true; &#x2F;&#x2F; Every invoker has the same weight value?                                                      &#x2F;&#x2F; @1 end</span><br><span class="line">        for (int i &#x3D; 0; i &lt; length; i++) &#123;                                                                                                                             &#x2F;&#x2F; @2 </span><br><span class="line">            Invoker&lt;T&gt; invoker &#x3D; invokers.get(i);</span><br><span class="line">            int active &#x3D; RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive(); &#x2F;&#x2F; Active number</span><br><span class="line">            int weight &#x3D; invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT); &#x2F;&#x2F;          </span><br><span class="line">                                                    &#x2F;&#x2F; Weight</span><br><span class="line">            if (leastActive &#x3D;&#x3D; -1 || active &lt; leastActive) &#123; &#x2F;&#x2F; Restart, when find a invoker having smaller least active value.              &#x2F;&#x2F; @3</span><br><span class="line">                leastActive &#x3D; active; &#x2F;&#x2F; Record the current least active value</span><br><span class="line">                leastCount &#x3D; 1; &#x2F;&#x2F; Reset leastCount, count again based on current leastCount</span><br><span class="line">                leastIndexs[0] &#x3D; i; &#x2F;&#x2F; Reset</span><br><span class="line">                totalWeight &#x3D; weight; &#x2F;&#x2F; Reset</span><br><span class="line">                firstWeight &#x3D; weight; &#x2F;&#x2F; Record the weight the first invoker</span><br><span class="line">                sameWeight &#x3D; true; &#x2F;&#x2F; Reset, every invoker has the same weight value?</span><br><span class="line">            &#125; else if (active &#x3D;&#x3D; leastActive) &#123; &#x2F;&#x2F; If current invoker&#39;s active value equals with leaseActive, then accumulating.       &#x2F;&#x2F; @4</span><br><span class="line">                leastIndexs[leastCount++] &#x3D; i; &#x2F;&#x2F; Record index number of this invoker</span><br><span class="line">                totalWeight +&#x3D; weight; &#x2F;&#x2F; Add this invoker&#39;s weight to totalWeight.</span><br><span class="line">                &#x2F;&#x2F; If every invoker has the same weight?</span><br><span class="line">                if (sameWeight &amp;&amp; i &gt; 0</span><br><span class="line">                        &amp;&amp; weight !&#x3D; firstWeight) &#123;</span><br><span class="line">                    sameWeight &#x3D; false;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        &#x2F;&#x2F; assert(leastCount &gt; 0)</span><br><span class="line">        if (leastCount &#x3D;&#x3D; 1) &#123;     &#x2F;&#x2F; @5</span><br><span class="line">            &#x2F;&#x2F; If we got exactly one invoker having the least active value, return this invoker directly.</span><br><span class="line">            return invokers.get(leastIndexs[0]);</span><br><span class="line">        &#125;</span><br><span class="line">        if (!sameWeight &amp;&amp; totalWeight &gt; 0) &#123;    &#x2F;&#x2F; @6</span><br><span class="line">            &#x2F;&#x2F; If (not every invoker has the same weight &amp; at least one invoker&#39;s weight&gt;0), select randomly based on totalWeight.</span><br><span class="line">            int offsetWeight &#x3D; random.nextInt(totalWeight);</span><br><span class="line">            &#x2F;&#x2F; Return a invoker based on the random value.</span><br><span class="line">            for (int i &#x3D; 0; i &lt; leastCount; i++) &#123;</span><br><span class="line">                int leastIndex &#x3D; leastIndexs[i];</span><br><span class="line">                offsetWeight -&#x3D; getWeight(invokers.get(leastIndex), invocation);</span><br><span class="line">                if (offsetWeight &lt;&#x3D; 0)</span><br><span class="line">                    return invokers.get(leastIndex);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        &#x2F;&#x2F; If all invokers have the same weight value or totalWeight&#x3D;0, return evenly.</span><br><span class="line">        return invokers.get(leastIndexs[random.nextInt(leastCount)]);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：解释相关局部变量。</p>
<ul>
<li>length ：服务提供者数量。</li>
<li> leastActive ：服务提供者的最小活跃连接数，初始化为-1。</li>
<li>  leastCount ：服务提供者中都是活跃连接数的个数，例如，3个服务提供者当前的活跃连接数分别为 100,102,100,则leastCount 为2。</li>
<li> leastIndexs：存放拥有活跃连接数的Invoker索引，例如上面100,102,100,则leastIndexs[0]=0， leastIndexs[1] = 2；</li>
<li>  totalWeight：拥有最小活跃连接数的Invoker的总权重。</li>
<li>  firstWeight ：第一个最小活跃连接数的Invoker的权重。</li>
<li>  sameWeight ：拥有最小活跃连接数的Invoker权重是否相同。</li>
</ul>
<p>代码@2：遍历所有的服务提供者，计算上述变量的值。</p>
<p>代码@3：如果leastActive （最小活跃连接数为-1，表示第一次遍历）或最新连接数大于当前遍历的Invoker的活跃连接数,需要reset如下值，重新计算：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">leastActive &#x3D; active; &#x2F;&#x2F; Record the current least active value</span><br><span class="line">leastCount &#x3D; 1; &#x2F;&#x2F; Reset leastCount, count again based on current leastCount leastIndexs[0] &#x3D; i; &#x2F;&#x2F; Reset</span><br><span class="line">totalWeight &#x3D; weight; &#x2F;&#x2F; Reset</span><br><span class="line">firstWeight &#x3D; weight; &#x2F;&#x2F; Record the weight the first invoker</span><br><span class="line">sameWeight &#x3D; true; &#x2F;&#x2F; Reset, every invoker has the same weight value?</span><br></pre></td></tr></table></figure>

<p>代码@4：如果当前遍历的服务提供者的活跃数等于leastActive ，则将总权重想加，并在leastIndexs中记录服务提供者序号。</p>
<p>代码@5，如果最小活跃连接数的服务提供者数量只有一个，则直接返回该服务提供者。</p>
<p>代码@6，如果最小活跃连接数的服务提供者有多个，则使用加权随机算法选取服务提供者。</p>
<p>关于Dubbo的4种负载均衡算法的实现细节就分析到这里了。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/b5542131.html" rel="next" title="源码分析Dubbo集群容错策略">
                <i class="fa fa-chevron-left"></i> 源码分析Dubbo集群容错策略
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/7c2dea71.html" rel="prev" title="源码分析Dubbo服务注册与发现机制RegistryDirectory)">
                源码分析Dubbo服务注册与发现机制RegistryDirectory) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90ConsistentHashLoadBalance%EF%BC%88%E4%B8%80%E8%87%B4%E6%80%A7Hash%E7%AE%97%E6%B3%95%EF%BC%89"><span class="nav-number">1.</span> <span class="nav-text">1、源码分析ConsistentHashLoadBalance（一致性Hash算法）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-%E6%A0%B8%E5%BF%83%E5%B1%9E%E6%80%A7%E4%B8%8E%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 核心属性与构造方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90public-Invoker-lt-T-gt-select-Invocation-invocation"><span class="nav-number">1.2.</span> <span class="nav-text">1.2 源码分析public Invoker&lt; T&gt; select(Invocation invocation)</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-1-ConsistentHashLoadBalance-ConsistentHashSelector-selectForKey"><span class="nav-number">1.2.1.</span> <span class="nav-text">1.2.1 ConsistentHashLoadBalance$ConsistentHashSelector#selectForKey</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90RandomLoadBalance"><span class="nav-number">2.</span> <span class="nav-text">2、源码分析RandomLoadBalance</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-Dubbo%E9%A2%84%E7%83%AD%E6%9C%BA%E5%88%B6%EF%BC%88%E6%9D%83%E9%87%8D%EF%BC%89"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 Dubbo预热机制（权重）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-RandomLoadBalance-%E5%8A%A0%E6%9D%83%E9%9A%8F%E6%9C%BA%E7%AE%97%E6%B3%95%E5%AE%9E%E7%8E%B0%E5%88%86%E6%9E%90"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 RandomLoadBalance 加权随机算法实现分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-RoundRobinLoadBalance-%E5%8A%A0%E6%9D%83%E8%BD%AE%E8%AF%A2%E7%AE%97%E6%B3%95%E5%88%86%E6%9E%90"><span class="nav-number">2.3.</span> <span class="nav-text">2.3 RoundRobinLoadBalance 加权轮询算法分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4-LeastActiveLoadBalance"><span class="nav-number">2.4.</span> <span class="nav-text">2.4 LeastActiveLoadBalance</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
